/**
 * 字典数据管理器
 * 提供字典数据的缓存、请求去重等功能
 */

class DictManager {
  constructor() {
    // 字典数据缓存
    this.cache = {};
    // 正在进行的请求，防止重复请求
    this.pendingRequests = {};
    // 缓存过期时间（毫秒）
    this.cacheExpireTime = 5 * 60 * 1000; // 5分钟
  }

  /**
   * 获取字典数据
   * @param {string} dictType 字典类型
   * @param {string} value 字典值
   * @returns {Promise} 返回字典项数据
   */
  async getDictItem(dictType, value) {
    if (!dictType || dictType === '') {
      console.warn('dictType is empty');
      return this.getDefaultItem(value);
    }

    const cacheKey = `${dictType}_${value}`;
    
    // 检查缓存
    if (this.cache[cacheKey] && !this.isCacheExpired(cacheKey)) {
      console.log('Using cached dict data for:', cacheKey);
      return Promise.resolve(this.cache[cacheKey]);
    }

    // 检查是否有正在进行的请求
    if (this.pendingRequests[dictType]) {
      console.log('Waiting for pending request:', dictType);
      return this.pendingRequests[dictType].then(dictList => {
        return this.findDictItem(dictList, value, cacheKey);
      });
    }

    // 发起新请求
    console.log('Fetching dict data for:', dictType);
    this.pendingRequests[dictType] = this.fetchDictData(dictType);

    try {
      const dictList = await this.pendingRequests[dictType];
      const result = this.findDictItem(dictList, value, cacheKey);
      
      // 清除pending状态
      delete this.pendingRequests[dictType];
      
      return result;
    } catch (error) {
      console.error('Failed to fetch dict data:', error);
      // 清除pending状态
      delete this.pendingRequests[dictType];
      
      return this.getDefaultItem(value);
    }
  }

  /**
   * 从字典列表中查找指定值的项
   */
  findDictItem(dictList, value, cacheKey) {
    const item = dictList.find(item => item.value == value);
    
    let result;
    if (!item) {
      result = this.getDefaultItem(value);
    } else {
      result = this.processDictItem(item);
    }
    
    // 缓存结果
    this.cache[cacheKey] = {
      data: result,
      timestamp: Date.now()
    };
    
    return result;
  }

  /**
   * 处理字典项数据
   */
  processDictItem(item) {
    const result = {...item};
    
    if (result.cssClass) {
      result.cssClass = result.cssClass.slice(4, result.cssClass.length);
    }
    
    if (result.cssStyle) {
      result.cssStyle = result.cssStyle.slice(6, result.cssStyle.length);
      if (result.cssStyle[result.cssStyle.length - 1] === ';') {
        result.cssStyle = result.cssStyle.slice(0, result.cssStyle.length - 1);
      }
    }
    
    return result;
  }

  /**
   * 获取默认字典项
   */
  getDefaultItem(value) {
    return {
      cssClass: '',
      cssStyle: '',
      name: value
    };
  }

  /**
   * 发起字典数据请求
   */
  async fetchDictData(dictType) {
    // 这里需要根据实际的API调用方式来实现
    // 由于无法直接访问this.$u.api，需要在组件中传入API实例
    throw new Error('fetchDictData method should be implemented by the caller');
  }

  /**
   * 检查缓存是否过期
   */
  isCacheExpired(cacheKey) {
    const cached = this.cache[cacheKey];
    if (!cached || !cached.timestamp) {
      return true;
    }
    
    return Date.now() - cached.timestamp > this.cacheExpireTime;
  }

  /**
   * 清除指定类型的缓存
   */
  clearCache(dictType) {
    if (dictType) {
      // 清除指定类型的缓存
      Object.keys(this.cache).forEach(key => {
        if (key.startsWith(dictType + '_')) {
          delete this.cache[key];
        }
      });
    } else {
      // 清除所有缓存
      this.cache = {};
    }
  }

  /**
   * 清除过期缓存
   */
  clearExpiredCache() {
    Object.keys(this.cache).forEach(key => {
      if (this.isCacheExpired(key)) {
        delete this.cache[key];
      }
    });
  }
}

// 创建全局实例
const dictManager = new DictManager();

export default dictManager;
